/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package com.je.bpm.engine.impl;

import com.je.bpm.engine.ActivitiIllegalArgumentException;
import com.je.bpm.engine.history.HistoricVariableInstance;
import com.je.bpm.engine.history.HistoricVariableInstanceQuery;
import com.je.bpm.engine.impl.context.Context;
import com.je.bpm.engine.impl.interceptor.CommandContext;
import com.je.bpm.engine.impl.interceptor.CommandExecutor;
import com.je.bpm.engine.impl.persistence.entity.HistoricVariableInstanceEntity;
import com.je.bpm.engine.impl.variable.CacheableVariable;
import com.je.bpm.engine.impl.variable.VariableTypes;

import java.util.List;
import java.util.Set;

public class HistoricVariableInstanceQueryImpl extends AbstractQuery<HistoricVariableInstanceQuery, HistoricVariableInstance> implements HistoricVariableInstanceQuery {

    private static final long serialVersionUID = 1L;
    protected String id;
    protected String taskId;
    protected Set<String> taskIds;
    protected String executionId;
    protected Set<String> executionIds;
    protected String processInstanceId;
    protected String activityInstanceId;
    protected String variableName;
    protected String variableNameLike;
    protected boolean excludeTaskRelated;
    protected boolean excludeVariableInitialization;
    protected QueryVariableValue queryVariableValue;

    public HistoricVariableInstanceQueryImpl() {
    }

    public HistoricVariableInstanceQueryImpl(CommandContext commandContext) {
        super(commandContext);
    }

    public HistoricVariableInstanceQueryImpl(CommandExecutor commandExecutor) {
        super(commandExecutor);
    }

    @Override
    public HistoricVariableInstanceQuery id(String id) {
        this.id = id;
        return this;
    }

    @Override
    public HistoricVariableInstanceQueryImpl processInstanceId(String processInstanceId) {
        if (processInstanceId == null) {
            throw new ActivitiIllegalArgumentException("processInstanceId is null");
        }
        this.processInstanceId = processInstanceId;
        return this;
    }

    @Override
    public HistoricVariableInstanceQueryImpl executionId(String executionId) {
        if (executionId == null) {
            throw new ActivitiIllegalArgumentException("Execution id is null");
        }
        this.executionId = executionId;
        return this;
    }

    @Override
    public HistoricVariableInstanceQueryImpl executionIds(Set<String> executionIds) {
        if (executionIds == null) {
            throw new ActivitiIllegalArgumentException("executionIds is null");
        }
        if (executionIds.isEmpty()) {
            throw new ActivitiIllegalArgumentException("Set of executionIds is empty");
        }
        this.executionIds = executionIds;
        return this;
    }

    public HistoricVariableInstanceQuery activityInstanceId(String activityInstanceId) {
        this.activityInstanceId = activityInstanceId;
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery taskId(String taskId) {
        if (taskId == null) {
            throw new ActivitiIllegalArgumentException("taskId is null");
        }
        if (excludeTaskRelated) {
            throw new ActivitiIllegalArgumentException("Cannot use taskId together with excludeTaskVariables");
        }
        this.taskId = taskId;
        return this;
    }

    @Override
    public HistoricVariableInstanceQueryImpl taskIds(Set<String> taskIds) {
        if (taskIds == null) {
            throw new ActivitiIllegalArgumentException("taskIds is null");
        }
        if (taskIds.isEmpty()) {
            throw new ActivitiIllegalArgumentException("Set of taskIds is empty");
        }
        if (excludeTaskRelated) {
            throw new ActivitiIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables");
        }
        this.taskIds = taskIds;
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery excludeTaskVariables() {
        if (taskId != null) {
            throw new ActivitiIllegalArgumentException("Cannot use taskId together with excludeTaskVariables");
        }
        if (taskIds != null) {
            throw new ActivitiIllegalArgumentException("Cannot use taskIds together with excludeTaskVariables");
        }
        excludeTaskRelated = true;
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery excludeVariableInitialization() {
        excludeVariableInitialization = true;
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableName(String variableName) {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("variableName is null");
        }
        this.variableName = variableName;
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableValueEquals(String variableName, Object variableValue) {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("variableName is null");
        }
        if (variableValue == null) {
            throw new ActivitiIllegalArgumentException("variableValue is null");
        }
        this.variableName = variableName;
        queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.EQUALS, true);
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableValueNotEquals(String variableName, Object variableValue) {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("variableName is null");
        }
        if (variableValue == null) {
            throw new ActivitiIllegalArgumentException("variableValue is null");
        }
        this.variableName = variableName;
        queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.NOT_EQUALS, true);
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableValueLike(String variableName, String variableValue) {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("variableName is null");
        }
        if (variableValue == null) {
            throw new ActivitiIllegalArgumentException("variableValue is null");
        }
        this.variableName = variableName;
        queryVariableValue = new QueryVariableValue(variableName, variableValue, QueryOperator.LIKE, true);
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableValueLikeIgnoreCase(String variableName, String variableValue) {
        if (variableName == null) {
            throw new ActivitiIllegalArgumentException("variableName is null");
        }
        if (variableValue == null) {
            throw new ActivitiIllegalArgumentException("variableValue is null");
        }
        this.variableName = variableName;
        queryVariableValue = new QueryVariableValue(variableName, variableValue.toLowerCase(), QueryOperator.LIKE_IGNORE_CASE, true);
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery variableNameLike(String variableNameLike) {
        if (variableNameLike == null) {
            throw new ActivitiIllegalArgumentException("variableNameLike is null");
        }
        this.variableNameLike = variableNameLike;
        return this;
    }

    protected void ensureVariablesInitialized() {
        if (this.queryVariableValue != null) {
            VariableTypes variableTypes = Context.getProcessEngineConfiguration().getVariableTypes();
            queryVariableValue.initialize(variableTypes);
        }
    }

    @Override
    public long executeCount(CommandContext commandContext) {
        checkQueryOk();
        ensureVariablesInitialized();
        return commandContext.getHistoricVariableInstanceEntityManager().findHistoricVariableInstanceCountByQueryCriteria(this);
    }

    @Override
    public List<HistoricVariableInstance> executeList(CommandContext commandContext, Page page) {
        checkQueryOk();
        ensureVariablesInitialized();

        List<HistoricVariableInstance> historicVariableInstances = commandContext.getHistoricVariableInstanceEntityManager().findHistoricVariableInstancesByQueryCriteria(this, page);

        if (!excludeVariableInitialization) {
            for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
                if (historicVariableInstance instanceof HistoricVariableInstanceEntity) {
                    HistoricVariableInstanceEntity variableEntity = (HistoricVariableInstanceEntity) historicVariableInstance;
                    if (variableEntity != null && variableEntity.getVariableType() != null) {
                        variableEntity.getValue();
                        //todo 此处去除了jpa的处理
                    }
                }
            }
        }
        return historicVariableInstances;
    }

    // order by
    // /////////////////////////////////////////////////////////////////
    @Override
    public HistoricVariableInstanceQuery orderByProcessInstanceId() {
        orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID);
        return this;
    }

    @Override
    public HistoricVariableInstanceQuery orderByVariableName() {
        orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME);
        return this;
    }

    // getters and setters
    // //////////////////////////////////////////////////////

    public String getProcessInstanceId() {
        return processInstanceId;
    }

    public String getTaskId() {
        return taskId;
    }

    public String getActivityInstanceId() {
        return activityInstanceId;
    }

    public boolean getExcludeTaskRelated() {
        return excludeTaskRelated;
    }

    public String getVariableName() {
        return variableName;
    }

    public String getVariableNameLike() {
        return variableNameLike;
    }

    public QueryVariableValue getQueryVariableValue() {
        return queryVariableValue;
    }
}
